//
//  ProfileApi.swift
//  WNLockDemo
//
//  Created by 裴威 on 01/09/2018.
//  Copyright © 2018 wunu. All rights reserved.
//

import Foundation
import Moya
import SwiftyJSON

/// 个人信息相关接口
///
/// - sendSmsCode: 发送短信验证码
/// - register: 注册
/// - login: 登录
/// - updateProfile: 更新用户信息
/// - accountInfo: 获取用户信息
/// - updateCellphone: 更新手机号码
enum ProfileApi {
    case sendSmsCode(phone: String)
    case register(parameters: [String: Any])
    case login(phone: String, password: String)
    case updateProfile(parameters: [String: Any])
    case accountInfo
    case updateCellphone(parameters: [String: Any])
}


extension ProfileApi: FxTargetType {
    var path: String {
        switch self {
        case .sendSmsCode:
            return "/weapp/sendSmsCode"
        case .register:
            return "/weapp/appRegister"
        case .login:
            return "/weapp/appLogin"
        case .updateProfile:
            return "/weapp/updateProfile"
        case .accountInfo:
            return "/weapp/accountInfo"
        case .updateCellphone:
            return "/weapp/updateCellphone"
        }
    }
    var method: Moya.Method {
        switch self {
        case .sendSmsCode,
             .register,
             .login,
             .updateProfile,
             .updateCellphone:
            return .post
        case .accountInfo:
            return .get
        }
    }
    var task: Task {
        switch self {
        case let .sendSmsCode(phone):
            return .requestParameters(parameters: ["cc": "86", "phone": phone], encoding: URLEncoding.default)
        case let .register(parameters),
             let .updateProfile(parameters),
             let .updateCellphone(parameters):
            return .requestParameters(parameters: parameters, encoding: URLEncoding.default)
        case let .login(phone, password):
            return .requestParameters(parameters: ["cc": "86", "phone": phone, "password": password], encoding: URLEncoding.default)
        case .accountInfo:
            return .requestPlain
        }
    }
    public var responseHandler: FxResponseHandler {
        return { json in
            let code = json["data"]["code"].intValue
            if code == 200 {
                switch self {
                case .login:
                    UserDefaults.standard.saveToken(token: json["data"]["data"]["token"].stringValue)
                default:
                    break
                }
                return .success(json["data"]["data"])
            } else {
                return .failure(NSError(domain: json["data"]["msg"].stringValue, code: json["data"]["code"].intValue, userInfo: nil))
            }
        }
    }
}
